package com.xhh.nphm.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhh.nphm.common.constant.Constants;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.QueryConditionVo;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.utils.CacheUtils;
import com.xhh.nphm.common.utils.DateUtils;
import com.xhh.nphm.common.utils.ShiroUtils;
import com.xhh.nphm.common.utils.poi.ExcelUtil;
import com.xhh.nphm.system.domain.*;
import com.xhh.nphm.system.mapper.CommonDao;
import com.xhh.nphm.system.mapper.SortMapper;
import com.xhh.nphm.system.service.*;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/mMailWF/cmnFile")
public class MMailWFcmnFileController extends BaseController {
    private final String prefix = "system/mMailWF/cmnFile";

    @Autowired
    private CommonDao commonDao;
    @Autowired
    private IMailGetDealService mailGetDealService;
    @Autowired
    private MmailWorkFormService mMailWorkFormService;
    @Autowired
    private MwfSendBackService mwfSendBackService;
    @Autowired
    private MMailWorkFormLogService mMailWorkFormLogService;
    @Autowired
    private ISprocessStepService sprocessStepService;
    @Autowired
    private IMmailWorkLogService mMailWorkLogService;

    @Autowired
    private IReplyTemplateService replyTemplateService;
    @Autowired
    private ITagService tagService;
    @Autowired
    private SortMapper sortMapper;
    @Autowired
    private IsGoBackConfService isGoBackConfService;
    @Autowired
    private ISmsNoteService smsNoteService;
    @Autowired
    private GetAWaitReplyMailService getAWaitReplyMailService;

    /**
     * 进入市级未签收列表页面
     */
    @GetMapping("/signNotList")
    public ModelAndView signNotList() {
        return new ModelAndView(prefix + "/signNotList");
    }

    /**
     * 加载市级未签收列表数据
     */
    @PostMapping("/signNotListJson")
    public TableDataInfo signNotListJson(MwfSendBack mwfSendBack,String workFormNo) {
        startPage();
        List<Map<String, Object>> list;
        if(IS_GAOXIN()){
            list = mwfSendBackService.signNotListJson_gxq(getSysUser().getDeptId().toString(),workFormNo,mwfSendBack);
        }else{
            list = mwfSendBackService.signNotListJson(getSysUser().getDeptId().toString(),workFormNo,mwfSendBack);
        }
        return getDataTable(list);
    }

    /**
     * 进入待本部门回复列表页面
     */
    @GetMapping("/replyWait")
    public ModelAndView replyWait(ModelMap map) {
        SysUser sysUser = getSysUser();
        map.put("sysUser",sysUser);
        return new ModelAndView(prefix + "/replyWait");
    }

    /**
     * 加载待本部门回复列表数据
     */
    @PostMapping("/replyWaitJson")
    public TableDataInfo replyWaitJson( QueryConditionVo qc) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.replyWaitJson(getSysUser().getDeptId().toString(),qc);
        return getDataTable(list);
    }

    /**
     * 加载待本部门回复列表数据
     * 高新区
     */
    @PostMapping("/replyWaitJson_gxq")
    public TableDataInfo replyWaitJson_gxq( QueryConditionVo qc) {
        String deptId = getSysUser().getDeptId().toString();
        int count = mwfSendBackService.dueWorkOrderCount(deptId);
        HashMap<String, Object> dueCount = new HashMap<>();
        dueCount.put("dueCount",count);
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.replyWaitJson_gxq(deptId,qc);
        for (Map<String, Object> map : list) {
            map.putAll(dueCount);
        }
        return getDataTable(list);
    }

    /**
     * 进入审核本部门回复列表页面
     */
    @GetMapping("/replyChk")
    public ModelAndView replyChk() {
        return new ModelAndView(prefix + "/replyChk");
    }

    /**
     * 加载审核本部门回复列表页面
     */
    @PostMapping("/replyChkJson")
    public TableDataInfo replyChkJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.replyChkJson(getSysUser().getDeptId(), workFormNo, sdeptName);
        return getDataTable(list);
    }

    /**
     * 进入本部门已办毕列表页面
     * @return 视图
     */
    @GetMapping("/replyOver")
    public ModelAndView replyOver() {
        return new ModelAndView(prefix + "/replyOver");
    }

    /**
     * 加载本部门已办毕列表数据
     * @return 列表数据
     */
    @PostMapping("/replyOverJson")
    public TableDataInfo replyOverJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName) {
        startPage();
        SysUser sysUser = getSysUser();
        String deptId = sysUser.getDeptId() == null ? null : sysUser.getDeptId().toString();
        List<Map<String, Object>> list = mwfSendBackService.replyOverJson(deptId, workFormNo, sdeptName);
        return getDataTable(list);
    }

    /**
     * 进入下级退回信件工单审核列表页面
     */
    @GetMapping("/mmReturnFlow")
    public ModelAndView mmReturnFlow() {
        return new ModelAndView(prefix + "/mmReturnFlow");
    }

    /**
     * 加载下级退回信件工单审核列表信息
     */
    @PostMapping("/mmReturnFlowJson")
    public TableDataInfo mmReturnFlowJson(MwfSendBack mwfSendBack,String workFormNo) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.mmReturnFlowJson(mwfSendBack,workFormNo);
        return getDataTable(list);
    }

    /**
     * 进入信件工单退回审核页面
     * @param sbId 信件拟派工单编号
     */
    @GetMapping("/mmReturnReason/{id}")
    public ModelAndView mmReturnReason(@PathVariable("id")Integer sbId, ModelMap map) {
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        map.put("userRole",getSysUser().getRoles().get(0).getRoleId());
        if (mwfSendBack != null) {
            map.put("sendBackEty",mwfSendBack);
            MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
            map.put("workFormBase", mmailWorkForm);
            map.put("smsInform",smsNoteService.selectSmsInformMail(getSysUser().getDeptId().toString(), getSysUser().getUserId().toString()));
        }
        return new ModelAndView(prefix + "/mmReturnReason");
    }

    /**
     * 信件工单退回审核
     *
     * @return
     */
    @PostMapping("/mmReturnPassTwoBackJson")
    public AjaxResult mmReturnPassTwoBackJson(MwfSendBack mwfSendBack, HttpServletRequest request) {
        SysUser user = ShiroUtils.getSysUser();
        QueryWrapper<MwfSendBack> queryWrapper = new QueryWrapper<>();
        //获取最新一轮的第一个派单
        queryWrapper.eq("wfId", mwfSendBack.getWfId());
        queryWrapper.eq("sdeptId", "304");
        queryWrapper.notIn("sendState",30,40);
        queryWrapper.orderByDesc("pkId");
        queryWrapper.select("top 1 pkId,sendTime");
        List<MwfSendBack> rootList = mwfSendBackService.list(queryWrapper);
        //当前部门下派的单子
        queryWrapper = new QueryWrapper<>();
        //条件isdel=0会自动加上
        queryWrapper.eq("wfId", mwfSendBack.getWfId());
        queryWrapper.eq("sdeptId",user.getDeptId());
        queryWrapper.notIn("sendState",30,40);
        if(rootList != null && rootList.size() > 0) {
            queryWrapper.gt("sendTime",rootList.get(0).getSendTime());
        }
        queryWrapper.orderByDesc("pkId");
        List<MwfSendBack> sendList2 = mwfSendBackService.list(queryWrapper);
        if(sendList2 != null && sendList2.size() > 0) {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("msg", "当前部门下派了多个部门，不能再退");
            ajaxResult.put("code", "470");
            return ajaxResult;
        }
        boolean resultFlag = true;
        mmReturnReasonJson(mwfSendBack,"", request);
        //查询需设置为再退的单子
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wfId", mwfSendBack.getWfId());
        queryWrapper.eq("sbDeptId",user.getDeptId());
        queryWrapper.notIn("sendState",30,40,51);
        if(rootList != null && rootList.size() > 0) {
            queryWrapper.ge("sendTime",rootList.get(0).getSendTime());
        }
        queryWrapper.orderByDesc("pkId");
        List<MwfSendBack> sendList = mwfSendBackService.list(queryWrapper);

        if(sendList != null && sendList.size() > 0) {
            //只取最新的一个派单，重复派单不管 设置为退回单
            MwfSendBack sendBack = sendList.get(0);
            UpdateWrapper<MwfSendBack> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("sendState", 40);
            updateWrapper.set("backState", 11);
            updateWrapper.set("flagInt", 1); //待审核
            updateWrapper.set("backRemark", mwfSendBack.getBackRemark());
            updateWrapper.eq("pkId", sendBack.getPkId());
            mwfSendBackService.update(updateWrapper);

            //记录退回操作日志
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(mwfSendBack.getWfId()); //[tWorkFormBase]PkId
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpBtnID(-1);
            etyLog.setOpAction("退回");
            etyLog.setWsDesc("退回工单。"); //Show In website
            if ("21".equals(mwfSendBack.getSortCode())) {
                etyLog.setWsOpen(0); //website ShowFlag
                etyLog.setEffectFlag(0);
            } else {
                etyLog.setWsOpen(1); //website ShowFlag
                etyLog.setEffectFlag(1);
            }
            //修改通过后在退回描述
            etyLog.setOpDesc("退回: " + mwfSendBack.getSdeptName() + "（" + mwfSendBack.getBackRemark() + "）");
            resultFlag = mMailWorkFormLogService.save(etyLog);
        }

        return toAjax(resultFlag);
    }
    /**
     * 信件工单退回审核
     *
     * @return
     */
    @PostMapping("/mmReturnReasonJson")
    public AjaxResult mmReturnReasonJson(MwfSendBack mwfSendBack,String isOpenThis, HttpServletRequest request) {
        boolean flag = true;boolean isSendNote = false;//发送短信
        MwfSendBack oldMwfSendBack = mwfSendBackService.getById(mwfSendBack.getPkId());
        // 防止多次点击通过或不通过
        if(oldMwfSendBack != null && !(oldMwfSendBack.getBackState() == 21 || (oldMwfSendBack.getBackState() == 0 && oldMwfSendBack.getSendState() == 51))) {
            SysUser user = ShiroUtils.getSysUser();
            // 同意 状态为 backState=21 不同意状态为backState=0 sendState=51
            //封装信件工单操作日志
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(mwfSendBack.getWfId());
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setLogTime(DateUtils.getNowDate());
            String desc = request.getParameter("opinion");
            String reason = request.getParameter("reason");
            String temp = "";
            if (reason.length() > 0) {
                temp = desc + "(" + reason + ")";
            } else {
                temp = desc;
            }
            if (mwfSendBack.getBackState() == 21) {
                //修改信件拟派工单
                UpdateWrapper<MwfSendBack> sbUpdateWrapper = new UpdateWrapper<>();
                sbUpdateWrapper
                        .set("SendRemark", temp)
                        .set("BackState", mwfSendBack.getBackState())
                        .set("FlagInt", 0)
                        .eq("PkId", mwfSendBack.getPkId());
                flag = mwfSendBackService.update(sbUpdateWrapper);
                // 退回到一级部门才修改工单状态
                if(304 == user.getDeptId()) {
                    //修改信件工单
                    UpdateWrapper<MmailWorkForm> wfUpdateWrapper = new UpdateWrapper<>();
                    wfUpdateWrapper
                            .set("WsUFlag", 1)
                            .set("CrtStepID", 401)
                            .set("CrtStepName", "市级" + mwfSendBack.getSortName() + "退回")
                            .set("CrtStepTime", DateUtils.getNowDate())
                            .eq("PkId", mwfSendBack.getWfId());
                    flag = mMailWorkFormService.update(wfUpdateWrapper);
                }
                //新增操作日志
                if (flag) {
                    temp = "通过";
                    temp = mwfSendBack.getSbdeptName() + "退回工单审核（" + temp + "）";
                    etyLog.setOpAction("审核退回工单");
                    etyLog.setOpBtnID(-1);
                    etyLog.setWsDesc(temp);
                    etyLog.setWsOpen(1);
                    etyLog.setOpDesc(temp);
                    etyLog.setEffectFlag(1);
                    flag = mMailWorkFormLogService.save(etyLog);
                }
            }
            else {
                //修改信件拟派工单
                UpdateWrapper<MwfSendBack> sbUpdateWrapper = new UpdateWrapper<>();
                sbUpdateWrapper
                        .set("SendRemark", temp)
                        .set("BackState", mwfSendBack.getBackState())
                        .set("SendState", 51)
                        .set("GetTime", DateUtils.getNowDate())
                        .set("GetPerson", user.getUserName())
                        .set("GetPerTel", user.getNoTel())
                        .set("BackRemark", "")
                        .set("FlagInt", 0)
                        .eq("PkId", mwfSendBack.getPkId());
                flag = mwfSendBackService.update(null, sbUpdateWrapper);
                //新增操作日志
                if (flag) {
                    temp = "不通过";
                    temp = mwfSendBack.getSbdeptName() + "退回工单审核（" + temp + "）";
                    etyLog.setOpAction("审核退回工单");
                    etyLog.setOpBtnID(-1);
                    etyLog.setWsDesc(temp);
                    etyLog.setWsOpen(0);
                    etyLog.setOpDesc(temp);
                    etyLog.setEffectFlag(-1);
                    flag = mMailWorkFormLogService.save(etyLog);
                    Integer smsInform = smsNoteService.selectSmsInformMail(user.getDeptId().toString(), user.getUserId().toString());
                    if(smsInform != null && smsInform == 1){ //11
                        if(isOpenThis != null && isOpenThis.equals("1")){
                            isSendNote = true;
                        }
                    }else {// 01
                        if(isOpenThis != null && isOpenThis.equals("1")){
                            isSendNote = true;
                        }
                    }
                }
            }
            if(isSendNote){
                smsNoteService.sendSmsNote(oldMwfSendBack.getSbdeptId(),mwfSendBack.getMyMwfNO(), "退回");
            }
        }
        return toAjax(flag);
    }

    /**
     * 进入市级未签收工单处理页面
     * @param sbId 信件拟派工单编号
     */
    @GetMapping("/dlSignS/{id}")
    public ModelAndView dlSignS(@PathVariable("id")Integer sbId, ModelMap map) {
        SysUser user = getSysUser();
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
        List<Map<String, Object>> mailExistTags = null;
        if (mwfSendBack != null) {
            map.put("pkId", mwfSendBack.getPkId());
            map.put("sortCode", mwfSendBack.getSortCode());
            map.put("sdeptName",mwfSendBack.getSdeptName());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("backLimit", format.format(mwfSendBack.getBackLimit()));
            map.put("sendBack", mwfSendBack);
            Object isGoBackToPeerDept = CacheUtils.get(Constants.USER_CACHE_KEY, Constants.IS_GOBACK + user.getDeptId());
            map.put("isGoBackToPeerDept",isGoBackConfService.checkPeerDeptIsGoBack(mwfSendBack.getSdeptId(),mwfSendBack.getSbdeptId()));
        }
        if (mmailWorkForm != null) {
            int mailId = Integer.valueOf(mmailWorkForm.getOriginFK());
            MmailGetDealEty mmailGetDeal = mailGetDealService.selectByPkId(mailId);
            if(mmailGetDeal != null) {
                map.put("ySpare", mmailGetDeal.getYspare());
            }
            map.put("workFormBase", mmailWorkForm);
            map.put("wfId", mmailWorkForm.getPkId());
            // 查询工单已有标签
            mailExistTags = tagService.selectMailExistTag(mmailWorkForm.getOriginFK(),user.getDeptId().toString(),user.getUserId().toString());
        }
        if(mailExistTags != null && mailExistTags.size() > 0){
            map.put("wfTag",mailExistTags);
        }
        map.put("user", user);
        //内容类别 完整展示三级分类
        String dcntAnameAll = getDcntAnameAll(mmailWorkForm);
        map.put("dcntAnameAll",dcntAnameAll);
        return new ModelAndView(prefix + "/dlSignS");
    }

    /**
     * 获取内容类别（三级完整展示）
     */
    public String getDcntAnameAll(MmailWorkForm mmailWorkForm){
        List list =new ArrayList();
        String dcntAnameAll="";
        if(mmailWorkForm!=null){
            String dcntAName = mmailWorkForm.getDcntAName();
            String dcntACode = mmailWorkForm.getDcntACode();
            if(dcntACode!=null&&!"".equals(dcntACode)){
                if (dcntAName!=null){
                    list.add(dcntAName);
                }
                BSort bSort = sortMapper.selectByCodePk(dcntACode);
                if(bSort!=null){
                    String codeparent = bSort.getCodeparent();
                    for(int j=0;!"11".equals(codeparent)&&j<2;j++){
                        BSort bSort1 = sortMapper.selectByCodePk(codeparent);
                        if(bSort1!=null){
                            list.add(bSort1.getSortname());
                            codeparent=bSort1.getCodeparent();
                        }else{
                            break;
                        }
                    }
                }
            }
            int size = list.size();
            if(size>0){
                for (int i=size-1;i>=0;i--){
                    dcntAnameAll=dcntAnameAll+list.get(i)+" ";
                }
            }
        }
        return dcntAnameAll;
    }

    /**
     * 待本部门回复-退回信件工单页面
     */
    @GetMapping("/dlBackS/{id}")
    public ModelAndView dlBackS(@PathVariable("id")Integer sbId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
        if (mwfSendBack != null) {
            map.put("wfId", mwfSendBack.getWfId());
            map.put("sendBackEty", mwfSendBack);
            map.put("isGoBackToPeerDept",isGoBackConfService.checkPeerDeptIsGoBack(mwfSendBack.getSdeptId(),mwfSendBack.getSbdeptId()));
        }
        if (mmailWorkForm != null) {
            map.put("workFormEty",mmailWorkForm);
        }
        map.put("sendId", sbId);
        map.put("user", user);
        return new ModelAndView(prefix + "/dlBackS");
    }

    /**
     * 进入回复本部门信件工单页面
     * @param sbId 拟派工单编号
     * @param map 模型
     * @return 视图
     */
    @GetMapping("/dlReplyS/{id}")
    public ModelAndView dlReplyS(@PathVariable("id")Integer sbId, Integer wfId, ModelMap map) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysUser user = getSysUser();
        map.put("user", user);
        map.put("sendId", sbId);
        map.put("nowTime", sdf.format(DateUtils.getNowDate()));
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        if (mwfSendBack != null) {
            map.put("wfId", mwfSendBack.getWfId());
            map.put("sendBackEty", mwfSendBack);
        }
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
        if (mmailWorkForm != null) {
            map.put("workFormEty",mmailWorkForm);
            int mailId = Integer.valueOf(mmailWorkForm.getOriginFK());
            MmailGetDealEty mmailGetDeal = mailGetDealService.selectByPkId(mailId);
            if(mmailGetDeal != null) {
                map.put("ySpare", mmailGetDeal.getYspare());
                map.put("wsCode", mmailGetDeal.getWsCode());
            }
        }
        List<MwfSendBack> subDeptHandleWF = mwfSendBackService.findSubDeptHandleWF(wfId, user.getDeptId());
        //两条及其以上时过滤掉groupIndex>1的数据
        if(subDeptHandleWF.size() > 1){
            subDeptHandleWF = subDeptHandleWF.stream().filter(val -> val.getGroupIndex() ==1).collect(Collectors.toList());
        }
        map.put("sonBackList",subDeptHandleWF);
        map.put("replyTemplate",replyTemplateService.selectMailRnByDeptOrUser(user.getDeptId().toString(), user.getUserNo()));
        return new ModelAndView(prefix + "/dlReplyS");
    }

    /**
     * 回复本部门信件工单
     * @return 视图
     */
    @PostMapping("/dlReplyS")
    public AjaxResult dlReplyS(MwfSendBack mwfSendBack,MmailWorkForm mmailWorkForm) {
        //保存响应结果
        boolean flag = false;
        String oldStr = mwfSendBack.getBackDesc();
        if(oldStr != null){
            mwfSendBack.setBackDesc(oldStr.replace(removeStr,""));
        }
        //修改派单表数据
        if (!Objects.isNull(mwfSendBack)) {
            UpdateWrapper<MwfSendBack> updateWrapper = new UpdateWrapper<>();
            updateWrapper
                    .set("backState", 10)
                    .set("bdutyDept", mwfSendBack.getBdutyDept())
                    .set("bdutyTel", mwfSendBack.getBdutyTel())
                    .set("buserNo", mwfSendBack.getBuserNo())
                    .set("buserName", mwfSendBack.getBuserName())
                    .set("backRemark", mwfSendBack.getBackRemark())
                    .set("backDesc", mwfSendBack.getBackDesc())
                    .set("backTime", mwfSendBack.getBackTime())
                    .set("battachPath", "")
                    .set("battachName", "")
                    .set("reason",mwfSendBack.getReason())
                    .eq("pkId", mwfSendBack.getPkId());
            flag = mwfSendBackService.update(updateWrapper);
            //更新父级派单状态
            commonDao.proMsubBackState(mwfSendBack.getWfId(),mwfSendBack.getPkId());
            //判断工单所有的派单部门都已办结完毕，完毕则修改工单状态
            if (!"21".equals(mwfSendBack.getSortCode())) {
                List tmpLst = mwfSendBackService.ltSendBackMain(mwfSendBack.getWfId(), mwfSendBack.getSdeptId());
                int myCounter = 0;
                for (int i = 0; i < tmpLst.size(); i++) {
                    MwfSendBack tmpEty = (MwfSendBack)tmpLst.get(i);
                    if (tmpEty.getBackState() > 0) {
                        myCounter++;
                    }
                }
                myCounter = tmpLst.size() - myCounter;
                if (myCounter == 0) {
                    //修改工单状态
                    UpdateWrapper<MmailWorkForm> etyUpdateWrapper = new UpdateWrapper<>();
                    etyUpdateWrapper
                            .set("wsUFlag", 1)
                            .set("crtStepId", mmailWorkForm.getCrtStepId())
                            .set("crtStepName", mmailWorkForm.getCrtStepName())
                            .set("crtStepTime", DateUtils.getNowDate())
                            .eq("pkId", mwfSendBack.getWfId());
                    flag = mMailWorkFormService.update(etyUpdateWrapper);
                }

            }
            //新增信件工单操作记录
            String desc = "回复：" + mwfSendBack.getSdeptName();
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            SysUser user = ShiroUtils.getSysUser();
            etyLog.setWfId(mwfSendBack.getWfId());
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpBtnID(-1);
            etyLog.setOpAction("回复");
            etyLog.setWsDesc("提交办理结果。");
            if ("21".equals(mwfSendBack.getSortCode())) {
                etyLog.setWsOpen(0);
                etyLog.setEffectFlag(0);
            } else {
                etyLog.setWsOpen(1);
                etyLog.setEffectFlag(1);
            }
            etyLog.setOpDesc(desc);
            etyLog.setLogTime(DateUtils.getNowDate());
            flag = mMailWorkFormLogService.save(etyLog);
        }
        return toAjax(flag);
    }

    /**
     * 进入审核回复页面
     * @param sbId 拟派工单id
     * @param map 模型
     * @return
     */
    @GetMapping("/dlChkReply/{id}")
    public ModelAndView dlChkReply(@PathVariable("id")Integer sbId, ModelMap map) {
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
        map.put("sendBackEty",mwfSendBack);
        map.put("workFormEty",mmailWorkForm);
        map.put("user",ShiroUtils.getSysUser());
        return new ModelAndView(prefix + "/dlChkReply");
    }

    /**
     * 审核本级回复
     */
    @PostMapping("/dlChkReply")
    public AjaxResult dlChkReply(MwfSendBack sendBackEty,MmailWorkForm mmailWorkForm,HttpServletRequest req) {
        // 保存响应结果
        boolean flag = false;
        // 当前登录用户
        SysUser user = getSysUser();
        // 获取审查意见
        String opinion = req.getParameter("opinion");
        // 获取不通过理由
        String reason = req.getParameter("reason");
        // 当前时间
        Date curDate = DateUtils.getNowDate();
        // fpAct
        int act = sendBackEty.getBackState();
        //修改信件派单表
        StringBuilder backRemark = new StringBuilder();
        backRemark.append(sendBackEty.getBackRemark() == null ? "" : sendBackEty.getBackRemark());
        backRemark.append("|");
        backRemark.append(opinion);
        backRemark.append("-");
        backRemark.append(reason);
        UpdateWrapper<MwfSendBack> sbWrapper = new UpdateWrapper<>();
        sbWrapper
                .set("backState", sendBackEty.getBackState())
                .set("backRemark", backRemark.toString())
                .set("backTime", curDate)
                .eq("pkId", sendBackEty.getPkId());
        flag = mwfSendBackService.update(sbWrapper);
        //修改信件工单表
        int iTmp = -9;
        if ((user.getDeptId().toString().length() == 3) || (user.getRoles().get(0).getRoleId() == 310) || (user.getRoles().get(0).getRoleId() == 340)) {
            iTmp = 9;
        }
        if ((iTmp > 0) && (!"21".equals(sendBackEty.getSortCode()))) {
            List tmpLst = mwfSendBackService.ltSendBackMain(sendBackEty.getWfId(), sendBackEty.getSdeptId());
            int myCounter = 0;
            String temp1 = "";
            for (int i = 0; i < tmpLst.size(); i++) {
                MwfSendBack tmpEty = (MwfSendBack) tmpLst.get(i);
                if (((11 == tmpEty.getBackState()) || (21 == tmpEty.getBackState())) && (40 != tmpEty.getSendState())) {
                    myCounter++;
                    temp1 = temp1 + tmpEty.getSbdeptName() + "(" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tmpEty.getBackTime()) + ")：\r\n" + tmpEty.getBackDesc() + "\r\n\r\n";
                }
            }
            myCounter = tmpLst.size() - myCounter;
            if (myCounter == 0) {
                UpdateWrapper<MmailWorkForm> wrapper = new UpdateWrapper<>();
                wrapper
                        .set("wsUFlag", 1)
                        .set("crtStepId", mmailWorkForm.getCrtStepId())
                        .set("crtStepName", mmailWorkForm.getCrtStepName())
                        .set("crtStepTIme", curDate)
                        .eq("pkId", sendBackEty.getWfId());
                if ((act == 11)) {
                    wrapper
                            .set("doverTime", curDate)
                            .set("doverDesc", temp1.toString());
                }
                flag = mMailWorkFormService.update(wrapper);
            }
        }
        //新增工单操作日志
        MMailWorkFormLog etyLog = new MMailWorkFormLog();
        etyLog.setWfId(sendBackEty.getWfId());
        etyLog.setOpDeptNo(user.getDeptId().toString());
        etyLog.setOpDeptName(user.getDeptName());
        etyLog.setOpUserNo(user.getUserNo());
        etyLog.setOpUserName(user.getUserName());
        etyLog.setLogTime(curDate);
        etyLog.setOpBtnID(-1);
        StringBuilder temp = new StringBuilder();
        if (act == 11) {
            etyLog.setOpAction("通过");
            temp.append(opinion);
        } else {
            etyLog.setOpAction("不通过");
            temp
                    .append("理由（")
                    .append(reason)
                    .append("）");
        }
        etyLog.setWsDesc(temp.toString());
        etyLog.setWsOpen(0);
        etyLog.setOpDesc(temp.toString());
        etyLog.setEffectFlag(0);
        flag = mMailWorkFormLogService.save(etyLog);
        return toAjax(flag, "审核成功");
    }

    /**
     * 退回信件拟派工单
     */
    @PostMapping("/dlBackS")
    public AjaxResult dlBackS(MwfSendBack mwfSendBack, HttpServletRequest request) {
        if (IS_GAOXIN()){
            return dlBackS_gxq(mwfSendBack);
        }else{
            return dlBackS_general(mwfSendBack,request);
        }
    }

    public AjaxResult dlBackS_general(MwfSendBack mwfSendBack, HttpServletRequest request) {
        //保存响应结果
        boolean flag = false;
        SysUser user = getSysUser();
        //修改信件拟派派工单
        UpdateWrapper<MwfSendBack> sbUpdateWrapper = new UpdateWrapper<>();
        sbUpdateWrapper
                .set("sendState",40)
                .set("getTime",DateUtils.getNowDate())
                .set("getPerson",user.getUserNo())
                .set("getPerTel",user.getNoTel())
                .set("backRemark",mwfSendBack.getBackRemark())
//                .set("SpareString",mwfSendBack.getSpareString())
                .set("backState",11)
                .set("flagInt",1)
                .eq("pkId",mwfSendBack.getPkId());
        flag = mwfSendBackService.update(sbUpdateWrapper);
        //新增工单操作日志
        flag = backLogDeal(mwfSendBack);
        //更新父级派单状态
        commonDao.proMsubBackState(mwfSendBack.getWfId(),mwfSendBack.getPkId());
        return toAjax(flag);
    }

    public AjaxResult dlBackS_gxq(MwfSendBack mwfSendBack) {
        //保存响应结果
        boolean flag = false;
        SysUser user = getSysUser();
        //修改信件拟派派工单
        UpdateWrapper<MwfSendBack> sbUpdateWrapper = new UpdateWrapper<>();
        sbUpdateWrapper
                .set("sendState",50)
                .set("getTime",DateUtils.getNowDate())
                .set("getPerson",user.getUserNo())
                .set("getPerTel",user.getNoTel())
                .set("backRemark",mwfSendBack.getBackRemark())
                .set("backState",11)
                .set("flagInt",1)
                .eq("pkId",mwfSendBack.getPkId());
        flag = mwfSendBackService.update(sbUpdateWrapper);
        //新增工单操作日志
        if(flag){
            String desc = "退回本级：" + mwfSendBack.getSdeptName();
            String signDesc = mwfSendBack.getBackRemark();
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(mwfSendBack.getWfId());
            etyLog.setSpareString(mwfSendBack.getSpareString());
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setLogTime(DateUtils.getNowDate());
            etyLog.setOpBtnID(-1);
            etyLog.setOpAction("退回本级");
            etyLog.setWsDesc("退回本级工单");
            if ("21".equals(mwfSendBack.getSortCode())) {
                etyLog.setWsOpen(0);
                etyLog.setEffectFlag(0);
            }
            else {
                etyLog.setWsOpen(1);
                etyLog.setEffectFlag(1);
            }
            etyLog.setOpDesc(desc + "（" + signDesc + "）");
            flag =  mMailWorkFormLogService.save(etyLog);
        }
        //更新父级派单状态
        commonDao.proMsubBackState(mwfSendBack.getWfId(),mwfSendBack.getPkId());
        return toAjax(flag);
    }

    /**
     * 签收信件工单
     * @param mwfSendBack 信件拟派工单
     * @param mmailWorkForm 信件工单
     * @return 响应结果
     */
    @PostMapping("/dlSignS")
    public AjaxResult dlSignS(MwfSendBack mwfSendBack,MmailWorkForm mmailWorkForm,HttpServletRequest request) {
        //保存响应结果
        boolean flag = false;
        //当前登录用户信息
        SysUser user = getSysUser();
        //当前时间
        Date curDate = DateUtils.getNowDate();
        //判断是市级还是区县，协办还是主办处理
        int act = Integer.parseInt(request.getParameter("fpDirect"));
        mwfSendBack.setBackRemark(request.getParameter("remark"));
        MwfSendBack mwfSendBackOld = mwfSendBackService.getById(mwfSendBack.getPkId());
        int sendStateOld = mwfSendBackOld.getSendState();
        if("21,22".indexOf(String.valueOf(sendStateOld)) == -1) {
            if(act == 21 || act == 22){
                //修改工单状态信息
                UpdateWrapper<MmailWorkForm> wrapper = new UpdateWrapper<>();
                wrapper
                        .set("crtStepId", mmailWorkForm.getCrtStepId())
                        .set("crtStepName", mmailWorkForm.getCrtStepName())
                        .set("crtStepTIme", curDate)
                        .eq("pkId", mwfSendBack.getWfId());
                if ((act == 22)) {
                    wrapper.set("wsUFlag", 1);
                }
                flag = mMailWorkFormService.update(wrapper);
            }
            //修改信件拟派派工单
            UpdateWrapper<MwfSendBack> sbUpdateWrapper = new UpdateWrapper<>();
            sbUpdateWrapper
                    .set("SendState",mwfSendBack.getSendState())
                    .set("PromisesTime",mwfSendBack.getPromisesTime())
                    .set("GetTime",curDate)
                    .set("GetPerson",user.getUserNo())
                    .set("GetPerTel",user.getNoTel())
                    .set("BackRemark",mwfSendBack.getBackRemark())
                    .set("BackState",0)
                    .eq("PkId",mwfSendBack.getPkId());
            flag = mwfSendBackService.update(sbUpdateWrapper);
            //新增工单签收操作日志
            flag = signLogDeal(mwfSendBack);
        }
        else {
            // 重复签收和待下派 不进行任何操作
            flag = true;
        }

        return toAjax(flag);
    }

    /**
     * 进入拟办部门页面
     */
    @GetMapping("/dlSendToSon/{pkId}")
    public ModelAndView sendDept(@PathVariable Integer pkId,Integer sbId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(pkId);
        // 查询工单已有标签
        List<Map<String, Object>> mailExistTags = null;
        if (mmailWorkForm != null){
            mailExistTags = tagService.selectMailExistTag(mmailWorkForm.getOriginFK(),user.getDeptId().toString(),user.getUserId().toString());
        }
        if(mailExistTags != null && mailExistTags.size() > 0){
            map.put("wfTag",mailExistTags);
        }
        MwfSendBack mwfSendBack = new MwfSendBack();
        mwfSendBack.setSdeptId(user.getDeptId().toString());
        mwfSendBack.setSdeptName(user.getDeptName());
        mwfSendBack.setSuserNo(user.getUserNo());
        mwfSendBack.setSuserName(user.getUserName());
        //TODO 设置办理期限 不是二级部门（锦江区），把派单的办理期限设置为父级派单办理期限
        if(sbId != null&sbId!=0) {
            MwfSendBack psendBack = mwfSendBackService.getById(sbId);
            map.put("pbackLimit", psendBack.getBackLimit());
            map.put("sendBack", psendBack);
        }
        else {
            QueryWrapper<MwfSendBack> queryWrapper = new QueryWrapper<MwfSendBack>();
            queryWrapper.eq("wfId", pkId);
            queryWrapper.eq("sbdeptId", user.getDeptId().toString());
            queryWrapper.eq("isDel", 0);
            List<MwfSendBack> list = mwfSendBackService.list(queryWrapper);
            if(list != null && list.size() > 0) {
                map.put("pbackLimit", list.get(0).getBackLimit());
            }
        }
        map.put("mmailWorkForm", mmailWorkForm);
        map.put("wfId", mmailWorkForm.getPkId());
        map.put("sbId", sbId);
        map.put("mailPk", mmailWorkForm.getOriginFK());
        map.put("sdeptName", user.getDept().getDeptShort());
        map.put("sdeptId", mwfSendBack.getSdeptId());
        map.put("suserName", mwfSendBack.getSuserName());
        map.put("suserNo", mwfSendBack.getSuserNo());
        map.put("deptId", user.getDeptId());
        map.put("sendTime", DateUtils.getTime());
        return new ModelAndView(prefix + "/dlSendToSon");
    }

    /**
     * 拟派工单承办部门选择
     * @param map
     * @return
     */
    @GetMapping("/deptAllM")
    public ModelAndView deptAllM(ModelMap map) {
        map.put("areaNo",getSysUser().getAreaNo());
        map.put("deptId",getSysUser().getDeptId());
        return new ModelAndView(prefix + "/deptAllM");
    }


    /**
     * 新增退回工单操作日志
     */
    private boolean backLogDeal(MwfSendBack mwfSendBack) {
        SysUser user = getSysUser();
        String desc = "退回：" + mwfSendBack.getSdeptName();
        String signDesc = mwfSendBack.getBackRemark();
        MMailWorkFormLog etyLog = new MMailWorkFormLog();
        etyLog.setWfId(mwfSendBack.getWfId());
        etyLog.setSpareString(mwfSendBack.getSpareString());
        etyLog.setOpDeptNo(user.getDeptId().toString());
        etyLog.setOpDeptName(user.getDeptName());
        etyLog.setOpUserNo(user.getUserNo());
        etyLog.setOpUserName(user.getUserName());
        etyLog.setLogTime(DateUtils.getNowDate());
        etyLog.setOpBtnID(-1);
        etyLog.setOpAction("退回");
        etyLog.setWsDesc("退回工单");
        if ("21".equals(mwfSendBack.getSortCode())) {
            etyLog.setWsOpen(0);
            etyLog.setEffectFlag(0);
        }
        else {
            etyLog.setWsOpen(1);
            etyLog.setEffectFlag(1);
        }
        etyLog.setOpDesc(desc + "（" + signDesc + "）");
        return mMailWorkFormLogService.save(etyLog);
    }

    /**
     * 新增签收工单操作日志
     */
    private boolean signLogDeal(MwfSendBack mwfSendBack) {
        SysUser user = getSysUser();
        String signDesc = mwfSendBack.getBackRemark();

        MMailWorkFormLog etyLog = new MMailWorkFormLog();
        etyLog.setWfId(mwfSendBack.getWfId());
        etyLog.setOpDeptNo(user.getDeptId().toString());
        etyLog.setOpDeptName(user.getDeptName());
        etyLog.setOpUserNo(user.getUserNo());
        etyLog.setOpUserName(user.getUserName());
        etyLog.setLogTime(DateUtils.getNowDate());
        etyLog.setOpBtnID(-1);
        etyLog.setOpAction("签收");
        etyLog.setWsDesc("签收工单");
        if ("21".equals(mwfSendBack.getSortCode())) {
            etyLog.setWsOpen(0);
            etyLog.setEffectFlag(0);
        }
        else {
            etyLog.setWsOpen(1);
            etyLog.setEffectFlag(1);
        }
        if (mwfSendBack.getSendState() != 22) {
            signDesc = signDesc == null || signDesc.equals("") ? "后续本单位办理" : "后续本单位办理（" + signDesc + "）";
        } else {
            signDesc = signDesc == null || signDesc.equals("") ? "后续转下级办理" : "后续转下级办理（" + signDesc + "）";
        }
        etyLog.setOpDesc(signDesc);
        return mMailWorkFormLogService.save(etyLog);
    }
    /**
     * 信件工单 重新办理 页面
     */
    @GetMapping("/flowRollBack/{pkId}")
    public ModelAndView flowRollBack(@PathVariable Integer pkId,ModelMap map) {
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(pkId);
        map.put("mmailWorkForm",mmailWorkForm);
        SprocessStepEty sprocessStepEty = sprocessStepService.getByProcess(mmailWorkForm.getSetProId(),mmailWorkForm.getCrtStepId());
        if (sprocessStepEty!=null) {
            map.put("sprocessStep", sprocessStepEty);
        }
        return new ModelAndView(prefix+"/flowRollBack");
    }
    /**
     * 信件工单 重新办理数据
     */
    @PostMapping("flowRollBackJson")
    @RequestBody
    public AjaxResult flowRollBackJson(MmailWorkForm mmailWorkForm,SprocessStepEty sprocessStepEty) {
        //获取工单当前信息
        UpdateWrapper<MmailWorkForm> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PkId", mmailWorkForm.getPkId());
        updateWrapper.set("CrtStepId", 120);
        updateWrapper.set("CrtStepName", "再次整理");
        updateWrapper.set("CrtStepTime", DateUtils.getNowDate());
        boolean flag = mMailWorkFormService.update(null, updateWrapper);
        if (flag) {
            //记录工单操作日志
            SysUser user = ShiroUtils.getSysUser();
            String desc = "撤回到：" + sprocessStepEty.getPreName();
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(Integer.parseInt(mmailWorkForm.getPkId()));
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpBtnID(-1);
            etyLog.setOpAction("撤回");
            etyLog.setWsDesc(desc);
            etyLog.setWsOpen(0);
            etyLog.setEffectFlag(1);
            etyLog.setOpDesc(desc);
            etyLog.setLogTime(new Date());
            mMailWorkFormLogService.save(etyLog);
        }
        return toAjax(flag);
    }

    /**
     * 信件工单 对应操作日志列表数据
     * @param wfId
     * @return
     */
    @PostMapping("flowRollBackLog/{wfId}")
    public TableDataInfo flowRollBackLog(@PathVariable Integer wfId) {
        startPage();
        List<MMailWorkFormLog> list=mMailWorkFormLogService.flowRollBackLog(wfId);
        return getDataTable(list);
    }



    /**
     * 进入上级不同意退回列表页面
     *
     * @return 视图
     */
    @GetMapping("/rNotPassList")
    public ModelAndView rNotPassList() {
        return new ModelAndView(prefix + "/rNotPassList");
    }


    /**
     * 加载上级不同意退回列表数据
     *
     * @return 列表数据
     */
    @PostMapping("/rNotPassListJson")
    public TableDataInfo rNotPassListJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.notPassListJson(getSysUser().getDeptId(),workFormNo,sdeptName);
        return getDataTable(list);
    }


    /**
     * 进入临期工单M列表页面
     *
     * @return 视图
     */
    @GetMapping("/muBlueS")
    public ModelAndView muBlueS() {
        return new ModelAndView(prefix + "/muBlueS");
    }


    /**
     * 加载临期工单M列表数据
     *
     * @return 列表数据
     */
    @PostMapping("/muBlueSJson")
    public TableDataInfo muBlueSJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.muBlueSJson(getSysUser().getDeptId(),workFormNo,sdeptName);
        return getDataTable(list);
    }

    /**
     * 进入超期工单M列表页面
     *
     * @return 视图
     */
    @GetMapping("/muRedS")
    public ModelAndView muRedS() {
        return new ModelAndView(prefix + "/muRedS");
    }


    /**
     * 加载临期工单M列表数据
     *
     * @return 列表数据
     */
    @PostMapping("/muRedSJson")
    public TableDataInfo muRedSJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.muRedSJson(getSysUser().getDeptId(),workFormNo,sdeptName);
        return getDataTable(list);
    }

    /**
     * 进入退回的工单列表页面
     */
    @GetMapping("/deptBack")
    public ModelAndView deptBack(){
        return new ModelAndView(prefix + "/deptBack");
    }

    /**
     * 加载退回的工单列表数据
     */
    @PostMapping("/deptBackJson")
    public TableDataInfo deptBackJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName){
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.deptBackJson(getSysUser().getDeptId(),workFormNo,sdeptName);
        return getDataTable(list);
    }

    /**
     * 进入办理结果审核页面
     */
    @GetMapping("/sendBackChk/{id}")
    public ModelAndView sendBackChk(@PathVariable("id")Integer sbId,ModelMap map){
        SysUser user = getSysUser();
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        map.put("userRole", user.getRoles().get(0).getRoleId());
        List<Map<String, Object>> mailExistTags = null;
        if (mwfSendBack != null) {
            map.put("sendBackEty",mwfSendBack);
            MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
            MwfSendBack pSendBackEty = mwfSendBackService.curDeptHandleSend(mwfSendBack.getWfId(), getSysUser().getDeptId().toString());
            if(pSendBackEty!=null){
                map.put("pSendBackEty",pSendBackEty);
            }
            map.put("workFormBase", mmailWorkForm);
            // 查询工单已有标签
            if(mmailWorkForm != null) {
                mailExistTags = tagService.selectMailExistTag(mmailWorkForm.getOriginFK(),user.getDeptId().toString(),user.getUserId().toString());
            }
        }
        if(mailExistTags != null && mailExistTags.size() > 0){
            map.put("wfTag",mailExistTags);
        }
        return new ModelAndView(prefix + "/sendBackChk");
    }

    /**
     * 审核办理结果
     */
    @PostMapping("/sendBackChk")
    public AjaxResult sendBackChk(MwfSendBack mwfSendBack,HttpServletRequest req){
        SysUser user = getSysUser();
        String desc = req.getParameter("opinion");
        String reason = req.getParameter("reason");
        String temp = "";
        if (reason.length() > 0){
            temp = desc + "(" + reason + ")";
        }else {
            temp = desc;
        }
        //修改信件拟派工单
        UpdateWrapper<MwfSendBack> sbUpdateWrapper = new UpdateWrapper<>();
        sbUpdateWrapper
                .set("SendRemark",temp)
                .set("BackState",mwfSendBack.getBackState())
                .eq("PkId",mwfSendBack.getPkId());
        //TODO 增加审核日志待完成
        boolean flag = mwfSendBackService.update(sbUpdateWrapper);
        //记录日志
        if (flag) {
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(mwfSendBack.getWfId());
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setLogTime(DateUtils.getNowDate());
            etyLog.setOpBtnID(-1);
            etyLog.setOpAction("审查结果");
            if (mwfSendBack.getBackState() == 22) {
                temp = "不通过";
            } else {
                temp = "通过";
            }
            temp = "审查" + mwfSendBack.getSbdeptName() + "办理结果（" + temp + "）";
            etyLog.setOpDesc(temp);
            etyLog.setWsDesc(temp);
            if ("21".equals(mwfSendBack.getSortCode())) {
                etyLog.setWsOpen(0);
                etyLog.setEffectFlag(0);
            }
            else {
                etyLog.setWsOpen(1);
                etyLog.setEffectFlag(1);
            }
            mMailWorkFormLogService.save(etyLog);
        }
        return toAjax(flag);
    }


    /**
     * 派单部门编辑页面
     */
    @GetMapping("/sendDeptEdit/{wfId}/{sbid}")
    public ModelAndView sendDeptEdit(@PathVariable Integer wfId, @PathVariable Integer sbid, ModelMap map) {
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(wfId);
        map.put("mmailWorkForm", mmailWorkForm);
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbid);
        map.put("mwfSendBack", mwfSendBack);
        return new ModelAndView(prefix + "/sendDeptEdit");
    }

    /**
     * 2023/1/9
     * 派单部门编辑页面
     */
    @GetMapping("/sendDeptEditPart/{sbid}")
    public ModelAndView sendDeptEditPart(@PathVariable Integer sbid, ModelMap map) {
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbid);
        map.put("mwfSendBack", mwfSendBack);
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
        map.put("mmailWorkForm", mmailWorkForm);
        return new ModelAndView(prefix + "/sendDeptEditPart");
    }


    /**
     * 进入派单管理列表页面
     */
    @GetMapping("/sendBackList/{wfId}")
    public ModelAndView sendBackList(@PathVariable Integer wfId,Integer pid,ModelMap map){
        map.put("wfId",wfId);
        map.put("pid",pid);
        return new ModelAndView(prefix + "/sendBackList");
    }

    /**
     * 加载派单管理列表数据
     */
    @PostMapping("/sendBackListJson")
    public TableDataInfo sendBackListJson(MwfSendBack sendBack){
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.sendBackListJson(sendBack,getSysUser().getDeptId());
        return getDataTable(list);
    }

    /**
     * 删除派单
     */
    @PostMapping("/removeSendBack")
    public AjaxResult removeSendBack(String... ids){
        return toAjax(mwfSendBackService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 撤回派单
     */
    @PostMapping("/returnBack/{id}")
    public AjaxResult returnBack(@PathVariable("id")Integer id){
        //修改信件拟派工单
        UpdateWrapper<MwfSendBack> sbUpdateWrapper = new UpdateWrapper<>();
        sbUpdateWrapper
                .set("SendState",30)
                .eq("PkId",id);
        boolean flag = mwfSendBackService.update(sbUpdateWrapper);
        MwfSendBack mwfSendBack = mwfSendBackService.getById(id);
        commonDao.proMsubBackState(mwfSendBack.getWfId(),id);
        return toAjax(flag);
    }


    /**
     * 下级办理结果页面
     */
    @GetMapping("/showSonBack/{wfId}")
    public ModelAndView showSonBack(@PathVariable("wfId") Integer wfId,Integer sbId, ModelMap map){
        List<MwfSendBack> listSendDept = mwfSendBackService.listSendSubDeptByPid(sbId,getSysUser().getDeptId());
        if(listSendDept == null || listSendDept.size() == 0){
            listSendDept = mwfSendBackService.listSendDeptSon(wfId,getSysUser().getDeptId());
        }else {
            List<MwfSendBack> listSendDeptSon = mwfSendBackService.listSendDeptSon(wfId, getSysUser().getDeptId());
            if(listSendDept.size() != listSendDeptSon.size()){
                listSendDept = listSendDeptSon;
            }
        }
        List<MwfSendBack[]> sonBackList = new ArrayList<>();
        if(!listSendDept.isEmpty()) {
            MwfSendBack[] sons = new MwfSendBack[3];
            for (int i = 0; i < listSendDept.size(); i++) {
                if (i % 3 == 0 && i != 0) {
                    sonBackList.add(sons);
                    sons = new MwfSendBack[3];
                }
                sons[i % 3] = listSendDept.get(i);
                if ((i + 1) == listSendDept.size()) {
                    sonBackList.add(sons);
                }
            }
        }
        map.put("sonBackList",sonBackList);
        return new ModelAndView(prefix + "/showSonBack");
    }


    /**
     * 来信信息、工单内容页面
     */
    @GetMapping("/showWorkForm/{wfId}")
    public ModelAndView showWorkForm(@PathVariable("wfId") Integer wfId,ModelMap map){
        SysUser user = getSysUser();
        map.put("user", user);
        MmailWorkForm workForm = mMailWorkFormService.getById(wfId);
        List<Map<String, Object>> mailExistTags = null;
        if(workForm != null){
            map.put("workForm",workForm);
            // 查询工单已有标签
            mailExistTags = tagService.selectMailExistTag(workForm.getOriginFK(),user.getDeptId().toString(),user.getUserId().toString());
        }
        if(mailExistTags != null && mailExistTags.size() > 0){
            map.put("wfTag",mailExistTags);
        }
        return new ModelAndView(prefix + "/showWorkForm");
    }


    /**
     * 进入撤回已退回的工单页面
     *
     * @author zz
     */
    @GetMapping("/dlRegetS")
    public ModelAndView dlRegetS(Integer sendId, ModelMap map) {
        map.put("sendBackEty", mwfSendBackService.getById(sendId));
        map.put("user", getSysUser());
        return new ModelAndView(prefix + "/dlRegetS");
    }

    /**
     * 进入撤回待分发到下级工单页面
     *
     * @author sjk
     */
    @GetMapping("/revokeSendSubM")
    public ModelAndView revokeSendSubM(Integer sendId, ModelMap map) {
        map.put("sendBackEty", mwfSendBackService.getById(sendId));
        map.put("user", getSysUser());
        return new ModelAndView(prefix + "/revokeSendSubM");
    }


    /**
     * 撤回已退回工单
     *
     * @author zz
     */
    @PostMapping("/dlRegetS")
    public AjaxResult dlRegetS(MwfSendBack sendBackEty,HttpServletRequest req) {
        //保存响应结果
        boolean flag = false;
        //获取当前登录用户信息
        SysUser user = getSysUser();
        //修改派单表记录
        UpdateWrapper<MwfSendBack> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .set("SendState", sendBackEty.getSendState())
                .set("GetTime", DateUtils.getNowDate())
                .set("GetPerson", user.getUserNo())
                .set("GetPerTel", user.getPhonenumber())
                .set("BackRemark", sendBackEty.getBackRemark())
                .set("BackState", 0)
                .eq("pkId", sendBackEty.getPkId());
        flag = mwfSendBackService.update(updateWrapper);
        //二级部门更新工单状态
        if("210,240,260,290,310,340".contains(user.getRoles().get(0).getRoleId().toString())){
            //更新工单
            UpdateWrapper<MmailWorkForm> wrap = new UpdateWrapper<>();
            wrap.eq("PkId", sendBackEty.getWfId());
            wrap.set("WsUFlag", 1);
            wrap.set("CrtStepID", req.getParameter("crtStepId"));
            wrap.set("CrtStepName", req.getParameter ("crtStepName"));
            wrap.set("CrtStepTime", DateUtils.getNowDate());
            mMailWorkFormService.update(null, wrap);
        }
        //新增工单操作日志
        rollLogDeal(sendBackEty);
        //设置父派单状态
        commonDao.proMsubBackState(sendBackEty.getWfId(),sendBackEty.getPkId());
        return toAjax(flag);
    }

    /**
     * 撤销退回日志记录
     */
    private void rollLogDeal(MwfSendBack send)
    {
        SysUser ssnUser = getSysUser();

        String mailWfId = String.valueOf(send.getWfId());
        String sortCode = send.getSortCode();
        String desc = "撤销退回：" + send.getSdeptName();
        String signDesc = send.getBackRemark() == null ? "无" : send.getBackRemark();

        MMailWorkFormLog etyLog = new MMailWorkFormLog();
        etyLog.setWfId(Integer.parseInt(mailWfId));
        etyLog.setOpDeptNo(String.valueOf(ssnUser.getDeptId()));
        etyLog.setOpDeptName(ssnUser.getDeptName());
        etyLog.setOpUserNo(ssnUser.getUserNo());
        etyLog.setOpUserName(ssnUser.getUserName());
        etyLog.setLogTime(new Date());

        etyLog.setOpBtnID(-1);
        etyLog.setOpAction("撤销退回(重新签收工单)");
        etyLog.setWsDesc("撤销退回。");
        if (sortCode.equals("21")) {
            etyLog.setWsOpen(0);
            etyLog.setEffectFlag(0);
        }
        else {
            etyLog.setWsOpen(1);
            etyLog.setEffectFlag(1);
        }
        etyLog.setOpDesc(desc + "（" + signDesc + "）");

        mMailWorkFormLogService.save(etyLog);
    }

    /**
     * 进入本部门已办毕工单编辑页面
     *
     * @param sendId 派单id
     */
    @GetMapping("/editReply")
    public ModelAndView editReply(Integer sendId, ModelMap map) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("user", ShiroUtils.getSysUser());
        map.put("nowTime", sdf.format(DateUtils.getNowDate()));
        map.put("sendBackEty", mwfSendBackService.getById(sendId));
        return new ModelAndView(prefix + "/editReply");
    }

    /**
     * 编辑本部门已办毕工单办理内容
     */
    @PostMapping("/editReply")
    public AjaxResult editReply(MwfSendBack sendBackEty) {
        String oldStr = sendBackEty.getBackDesc();
        if(oldStr!=null){
            sendBackEty.setBackDesc(oldStr.replace(removeStr,""));
        }
        //修改办理内容
        UpdateWrapper<MwfSendBack> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .set("GetPerson", sendBackEty.getGetPerson())
                .set("BDutyTel", sendBackEty.getBdutyTel())
                .set("BDutyDept", sendBackEty.getBdutyDept())
                .set("BUserName", sendBackEty.getBuserName())
                .set("BackTime", sendBackEty.getBackTime())
                .set("BackDesc", sendBackEty.getBackDesc())
                .set("BackRemark", sendBackEty.getBackRemark())
                .eq("PkId", sendBackEty.getPkId());
        return toAjax(mwfSendBackService.update(updateWrapper));
    }

    /**
     * （网络理政区县）信件未回复工单页面
     * @param wfId 工单编号
     * @param map
     * @return
     */
    @RequestMapping("/mailReplyWllz/{wfId}")
    public ModelAndView mailReplyWllz(@PathVariable("wfId")Integer wfId,ModelMap map){
//        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(wfId);
        map.put("wfId", wfId);
//        if (mwfSendBack != null) {
//            map.put("sendBackEty", mwfSendBack);
//        }
        if (mmailWorkForm != null) {
            map.put("workFormEty",mmailWorkForm);
            int mailId = Integer.valueOf(mmailWorkForm.getOriginFK());
            MmailGetDealEty mmailGetDeal = mailGetDealService.selectByPkId(mailId);
            if(mmailGetDeal != null) {
                map.put("ySpare", mmailGetDeal.getYspare());
                map.put("wsCode", mmailGetDeal.getWsCode());
            }
        }
//        map.put("sendId", sbId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("nowTime", sdf.format(DateUtils.getNowDate()));
        map.put("user", ShiroUtils.getSysUser());
        List<MwfSendBack> listSendDept = mwfSendBackService.listSendDeptSon(wfId,getSysUser().getDeptId());
        List<MwfSendBack[]> sonBackList = new ArrayList<>();
        if(!listSendDept.isEmpty()) {
            MwfSendBack[] sons = new MwfSendBack[3];
            for (int i = 0; i < listSendDept.size(); i++) {
                if (i % 2 == 0 && i != 0) {
                    sonBackList.add(sons);
                    sons = new MwfSendBack[3];
                }
                sons[i % 2] = listSendDept.get(i);
                if ((i + 1) == listSendDept.size()) {
                    sonBackList.add(sons);
                }
            }
        }
        map.put("sonBackList",sonBackList);
        return new ModelAndView(prefix + "/mailReplyWllz");
    }

    /**
     * （网络理政区县）回复信件工单
     * @return 影响结果
     */
    @PostMapping("/mailReplyWllz/{wfId}")
    public AjaxResult mailReplyWllz(@PathVariable("wfId") String wfId,HttpServletRequest request){
        boolean rtnFlag = false;

        SysUser ssnUser = getSysUser();
        String myOpTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        String sortCode = "";
        String userNo = ssnUser.getUserNo();
        String deptNo = ssnUser.getDeptId().toString();
        String deptName = ssnUser.getDeptName();
        String backFlag = "10";
        String backDesc = request.getParameter("taBackDesc");

        UpdateWrapper<MmailWorkForm> wrapper = new UpdateWrapper<>();
        wrapper.set("SBackState",backFlag);
        wrapper.set("DOverTime",DateUtils.getNowDate());
        wrapper.set("DOverDesc",backDesc);
        wrapper.eq("PkId",wfId);
        rtnFlag = mMailWorkFormService.update(wrapper);

        String stepId = "950";
        String stepName = "归档";

        String tbFromDept = request.getParameter("tbFromDept");
        List tmpLst = mwfSendBackService.ltSendBackMain(Integer.parseInt(wfId), deptNo);
        int myCounter = 0;
        for (int i = 0; i < tmpLst.size(); i++) {
            MwfSendBack tmpEty = (MwfSendBack)tmpLst.get(i);

            if (tmpEty.getBackState() > 0) {
                myCounter++;
            }

        }

        if (myCounter > 0) {
            UpdateWrapper<MmailWorkForm> updateWrap = new UpdateWrapper<>();
            updateWrap.set("CrtStepId",stepId);
            updateWrap.set("CrtStepName",stepName);
            updateWrap.set("CrtStepTime",myOpTime);
            updateWrap.eq("PkId",wfId);
            rtnFlag = mMailWorkFormService.update(updateWrap);
        }

        String desc = "回复：" + (StringUtils.isEmpty(tbFromDept) ? deptName : tbFromDept);
        MMailWorkFormLog etyLog = new MMailWorkFormLog();
        etyLog.setWfId(Integer.parseInt(wfId));
        etyLog.setOpDeptNo(deptNo);
        etyLog.setOpDeptName(deptName);
        etyLog.setOpUserNo(userNo);
        etyLog.setOpUserName(ssnUser.getUserName());

        etyLog.setOpBtnID(-1);
        etyLog.setOpAction("回复");
        etyLog.setWsDesc("提交办理结果");
        if ((sortCode == null) || (sortCode.equals("21"))) {
            etyLog.setWsOpen(0);
            etyLog.setEffectFlag(0);
        } else {
            etyLog.setWsOpen(1);
            etyLog.setEffectFlag(1);
        }
        etyLog.setOpDesc(desc);
        etyLog.setLogTime(new Date());
        mMailWorkFormLogService.save(etyLog);
        return toAjax(rtnFlag);
    }


    /**
     * 签收后直接回复工单页面
     * @param sbId 拟派工单编号
     * @param map 模型
     * @return 视图
     */
    @GetMapping("/replyAfterSignS/{id}")
    public ModelAndView replyAfterSignS(@PathVariable("id")Integer sbId, Integer wfId, ModelMap map) {
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
        if (mwfSendBack != null) {
            map.put("wfId", mwfSendBack.getWfId());
            map.put("sendBackEty", mwfSendBack);
        }
        if (mmailWorkForm != null) {
            map.put("workFormEty",mmailWorkForm);
            int mailId = Integer.valueOf(mmailWorkForm.getOriginFK());
            MmailGetDealEty mmailGetDeal = mailGetDealService.selectByPkId(mailId);
            if(mmailGetDeal != null) {
                map.put("ySpare", mmailGetDeal.getYspare());
                map.put("wsCode", mmailGetDeal.getWsCode());
            }
        }
        map.put("sendId", sbId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("nowTime", sdf.format(DateUtils.getNowDate()));
        map.put("user", ShiroUtils.getSysUser());
        return new ModelAndView(prefix + "/replyAfterSignS");
    }

    /**
     * 签收后直接回复并审核工单页面
     * @param sbId 拟派工单编号
     * @param map 模型
     * @return 视图
     */
    @GetMapping("/replyAfterAudit/{id}")
    public ModelAndView replyAfterAudit(@PathVariable("id")Integer sbId, Integer wfId, ModelMap map) {
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
        if (mwfSendBack != null) {
            map.put("wfId", mwfSendBack.getWfId());
            map.put("sendBackEty", mwfSendBack);
        }
        if (mmailWorkForm != null) {
            map.put("workFormEty",mmailWorkForm);
            int mailId = Integer.valueOf(mmailWorkForm.getOriginFK());
            MmailGetDealEty mmailGetDeal = mailGetDealService.selectByPkId(mailId);
            if(mmailGetDeal != null) {
                map.put("ySpare", mmailGetDeal.getYspare());
                map.put("wsCode", mmailGetDeal.getWsCode());
            }
        }
        map.put("sendId", sbId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("nowTime", sdf.format(DateUtils.getNowDate()));
        map.put("user", ShiroUtils.getSysUser());
        return new ModelAndView(prefix + "/replyAfterAudit");
    }


    /**
     * 批量审核回复页面
     * @param ids 派单ids
     */
    @GetMapping("/dlBatchChkReply")
    public ModelAndView dlBatchChkReply(String ids,ModelMap map){
        map.put("ids",ids);
        return new ModelAndView(prefix + "/dlBatchChkReply");
    }


    /**
     * 批量审核回复
     * @param ids 派单ids
     * @param act 通过与否
     */
    @PostMapping("/dlBatchChkReply")
    public AjaxResult dlBatchChkReplyJson(@RequestParam("ids") String ids,@RequestParam("act")int act,HttpServletRequest req){
        //保存影响结果
        AjaxResult res = AjaxResult.warn("操作失败");

        //被审核的派单id列表
        String[] idList = ids.split(",");
        SysUser user = getSysUser();

        for (String id : idList) {
            //派单对象
            MwfSendBack sendBackEty = mwfSendBackService.getById(Integer.parseInt(id));
            if(act < 1) {
                sendBackEty.setBackState(12);
            }else{
                sendBackEty.setBackState(11);
            }
            //工单对象
            MmailWorkForm workFormEty = mMailWorkFormService.getById(sendBackEty.getWfId());
            if("210,240,260,290,310,340".contains(user.getRoles().get(0).getRoleId().toString())){
                if(Integer.parseInt(sendBackEty.getSortCode()) == 11){
                    //普通工单
                    if(workFormEty.getSetProId() == 11){
                        workFormEty.setCrtStepId(900);
                        workFormEty.setCrtStepName("待回访");
                    }
                    if (act < 1) {
                        workFormEty.setCrtStepId(801);
                        workFormEty.setCrtStepName("市级不通过");
                    }
                }
            }
            //调用审核单个派单回复的方法
            res = dlChkReply(sendBackEty,workFormEty,req);
        }
        return res;
    }

    /**
     * 信件工单内容编辑页面
     * @param id 工单编号
     */
    @GetMapping("/mWFormCreate/{id}")
    public ModelAndView mWFormCreate(@PathVariable("id")String id,ModelMap map){
        map.put("mmailWorkForm",mMailWorkFormService.getById(Integer.parseInt(id)));
        return new ModelAndView(prefix + "/mWFormCreate");
    }

    /**
     * 编辑信件工单内容
     * @param mailWorkForm 修改后的工单内容
     */
    @PostMapping("/mWFormCreateJson")
    public AjaxResult mWFormCreateJson(MmailWorkForm mailWorkForm){
        //保存影响结果
        boolean flag = false;
        //修改工单内容
        MmailWorkForm workForm = mMailWorkFormService.getById(mailWorkForm.getPkId());
        workForm.setFromName(mailWorkForm.getFromName());
        workForm.setFmEmail(mailWorkForm.getFmEmail());
        workForm.setFromSex(mailWorkForm.getFromSex());
        workForm.setFromTel(mailWorkForm.getFromTel());
        workForm.setFmAddress(mailWorkForm.getFmAddress());
        workForm.setFromTopic(mailWorkForm.getFromTopic());
        workForm.setFmContent(mailWorkForm.getFmContent());
        workForm.setOpenFrom(mailWorkForm.getOpenFrom());
        workForm.setDfmClaNo(mailWorkForm.getDfmClaNo());
        workForm.setDfmClaName(mailWorkForm.getDfmClaName());
        workForm.setDcntACode(mailWorkForm.getDcntACode());
        workForm.setDcntAName(mailWorkForm.getDcntAName());
        workForm.setSetProId(mailWorkForm.getSetProId());
        workForm.setSetProName(mailWorkForm.getSetProName());
        workForm.setOpenX(mailWorkForm.getOpenX());
        workForm.setReportFlag(mailWorkForm.getReportFlag());
        workForm.setWfRemark(mailWorkForm.getWfRemark());
        flag = mMailWorkFormService.updateById(workForm);
        //修改信件
        UpdateWrapper<MmailGetDealEty> wrapper = new UpdateWrapper<>();
        wrapper.set("YWorkNo",getSysUser().getUserNo());
        wrapper.set("YWorker",getSysUser().getUserName());
        wrapper.set("OpenX",workForm.getOpenX());
        wrapper.eq("PkId",workForm.getOriginFK());
        flag = mailGetDealService.update(wrapper);
        return toAjax(flag);
    }

    /**
     * @Description: 修改回复内容
     * @Param: [mwfSendBack]
     * @return: AjaxResult
     */
    @PostMapping("/btnReplyClick")
    public AjaxResult btnReplyClick(MwfSendBack mwfSendBack){
        SysUser sysUser = getSysUser();
        String oldStr = mwfSendBack.getBackDesc();
        if(oldStr!=null){
            mwfSendBack.setBackDesc(oldStr.replace(removeStr,""));
        }
        UpdateWrapper<MwfSendBack> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .set("Reason",mwfSendBack.getReason())
                .set("BUserName", sysUser.getUserName())
                .set("BDutyDept", sysUser.getDeptName())
                .set("BDutyTel", sysUser.getNoTel())
                .set("BackTime",new Date())
                .set("BackDesc",mwfSendBack.getBackDesc())
                .set("BackRemark",mwfSendBack.getBackRemark())
                .eq("PkId",mwfSendBack.getPkId());
        boolean flag = mwfSendBackService.update(null,updateWrapper);
        //记录日志
        if(flag){
            MmailWorkLogEty mailWorkLog = new MmailWorkLogEty();
            mailWorkLog.setWfId(mwfSendBack.getWfId());
            mailWorkLog.setLogTime(new Date());
            mailWorkLog.setOpDeptNo(sysUser.getDeptId().toString());
            mailWorkLog.setOpDeptName(sysUser.getDeptName());
            mailWorkLog.setOpUserNo(sysUser.getUserNo());
            mailWorkLog.setOpUserName(sysUser.getUserName());
            mailWorkLog.setOpAction("修改");
            mailWorkLog.setOpBtnId(-1);
            mailWorkLog.setWsDesc("修改回复内容");
            mailWorkLog.setWsOpen(0); //默认不公开
            mailWorkLog.setOpDesc("修改回复内容");
            mailWorkLog.setEffectFlag(-1);
            mMailWorkLogService.save(mailWorkLog);
        }
        return toAjax(flag);
    }


    /**
     * 进入已删除信件工单页面
     */
    @GetMapping("/deletedMailWF")
    public ModelAndView deletedMailWF() {
        return new ModelAndView(prefix + "/deletedMailWF");
    }

    /**
     * 加载已删除信件工单列表数据
     */
    @PostMapping("/deletedMailWFJson")
    public TableDataInfo deletedMailWFJson(MwfSendBack mwfSendBack,String workFormNo) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.deletedMailWFList(getSysUser().getDeptId().toString(),workFormNo,mwfSendBack);
        return getDataTable(list);
    }

    /**
     * 进入未签收列表 同源派单页面
     */
    @GetMapping("/searchForm")
    public ModelAndView searchForm() {
        return new ModelAndView(prefix + "/searchForm");
    }

    /**
     * 加载未签收列表 同源派单数据
     */
    @PostMapping("/notSignList")
    public TableDataInfo notSignList(MwfSendBack mwfSendBack) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.notSignListJson(getSysUser().getDeptId().toString(),mwfSendBack);
        return getDataTable(list);
    }

    /**
     * 批量派单页面
     * @return
     */
    @GetMapping("/batchSendToSon")
    public ModelAndView batchSendToSon(Integer times, ModelMap map){
        SysUser user = getSysUser();
        map.put("deptId", user.getDeptId());
        map.put("sdeptId",user.getDeptId());//派发单位
        map.put("sdeptName",user.getDeptName());//派发单位
        map.put("suserNo",user.getUserNo());//派发人
        map.put("suserName",user.getUserName());//派发人
        if(times != null && times == 1){
            map.put("seqCode",10);
            map.put("seqName","初次交办");
        }else if(times != null && times == 2){
            map.put("seqCode",20);
            map.put("seqName","再次交办");
        }
        return new ModelAndView(prefix+"/batchSendToSon");
    }

    /**
     * 进入未签收列表 同源派单页面
     */
    @GetMapping("/searchReplyForm")
    public ModelAndView searchReplyForm() {
        return new ModelAndView(prefix + "/searchReplyForm");
    }

    /**
     * 进入待回复列表 同源再派数据
     */
    @PostMapping("/waitReplyList")
    public TableDataInfo waitReplyList(MwfSendBack mwfSendBack) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.waitReplyListJson(getSysUser().getDeptId().toString(),mwfSendBack);
        return getDataTable(list);
    }

    /**
     * 通过并再回
     */
    @GetMapping("/passOrReply")
    public ModelAndView passOrReply(Integer sbId, Integer wfId, ModelMap map) {
        MwfSendBack mwfSendBack = mwfSendBackService.curDeptHandleSend(wfId, getSysUser().getDeptId().toString());
        if (mwfSendBack != null) {
            map.put("sendBackEty", mwfSendBack);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("nowTime", sdf.format(DateUtils.getNowDate()));
        map.put("user", ShiroUtils.getSysUser());
        List<MwfSendBack> listSendDept = mwfSendBackService.listSendSubDeptByPid(sbId,getSysUser().getDeptId());
        if(listSendDept == null || listSendDept.size() == 0){
            listSendDept = mwfSendBackService.listSendDeptSon(wfId,getSysUser().getDeptId());
        } else {
            List<MwfSendBack> listSendDeptSon = mwfSendBackService.listSendDeptSon(wfId, getSysUser().getDeptId());
            if(listSendDept.size() != listSendDeptSon.size()){
                listSendDept = listSendDeptSon;
            }
        }
        map.put("sonBackList",listSendDept);
        map.put("replyTemplate",replyTemplateService.selectMailRnByDeptOrUser(getSysUser().getDeptId().toString(),getSysUser().getUserNo()));
        map.put("sendId",sbId);
        map.put("wfId",wfId);
        return new ModelAndView(prefix + "/passOrReply");
    }

    /**
     * 进入未处理信件工单页面
     */
    @GetMapping("/notHandleMailList")
    public ModelAndView notHandleMailList() {
        return new ModelAndView(prefix + "/notHandleMailList");
    }

    /**
     * 加载未处理信件工单数据
     */
    @PostMapping("/notHandleMailJson")
    public TableDataInfo notHandleMailJson(MwfSendBack mwfSendBack) {
        startPage();
        List<Map<String, Object>> list;
        if(IS_GAOXIN()){
            list = mwfSendBackService.notHandleMailJson_gxq(getSysUser().getDeptId().toString(),mwfSendBack);
        }else{
            list = mwfSendBackService.notHandleMailJson(getSysUser().getDeptId().toString(),mwfSendBack);
        }
        return getDataTable(list);
    }

    /**
     * 导出未处理信件工单数据
     */
    @PostMapping("/notHandleMailExport")
    @ResponseBody
    public AjaxResult notHandleMailExport() {
        SysUser user = getSysUser();
        List<NotHandleMailExcel> list = mwfSendBackService.notHandleMailExport(user.getDeptId().toString());
        ExcelUtil<NotHandleMailExcel> util = new ExcelUtil<>(NotHandleMailExcel.class);
        return util.exportExcel(list, "未处理信件工单数据");
    }

    /**
     * 进入上级催办信件工单页面
     */
    @GetMapping("/supUrgeMailOrder")
    public ModelAndView supUrgeMailOrder() {
        return new ModelAndView(prefix + "/supUrgeMailOrder");
    }

    /**
     * 加载上级催办信件工单数据
     */
    @PostMapping("/supUrgeMailOrderJson")
    public TableDataInfo supUrgeMailOrderJson(MwfSendBack mwfSendBack) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.supUrgeMailOrderJson(getSysUser().getDeptId().toString(),mwfSendBack);
        return getDataTable(list);
    }

    /**
     * 导出上级催办信件工单数据
     */
    @PostMapping("/supUrgeMailOrderExport")
    @ResponseBody
    public AjaxResult supUrgeMailOrderExport() {
        SysUser user = getSysUser();
        List<SupUrgeMailExcel> list = mwfSendBackService.supUrgeMailOrderExport(user.getDeptId().toString());
        ExcelUtil<SupUrgeMailExcel> util = new ExcelUtil<>(SupUrgeMailExcel.class);
        return util.exportExcel(list, "上级催办信件工单数据");
    }

    /**
     * 拟派工单承办部门选择
     * @param map
     * @return
     */
    @GetMapping("/copyDeptAll")
    public ModelAndView copyDeptAll(ModelMap map) {
        map.put("areaNo",getSysUser().getAreaNo());
        map.put("deptId",getSysUser().getDeptId());
        return new ModelAndView(prefix + "/copyDeptAll");
    }

    /**
     * 进入审核本级回复 -- 获取未处理列表页面
     * @return 视图
     */
    @GetMapping("/getPeerReplyOverUntreatedM")
    public ModelAndView getPeerReplyOverUntreatedM(ModelMap map) {
        map.put("num",mwfSendBackService.countReplyChkJson(getSysUser().getDeptId()));
        return new ModelAndView(prefix + "/getPeerReplyOverUntreatedM");
    }

    /**
     * 加载审核本部门回复列表数据
     * 高新区
     */
    @PostMapping("/getReplyChkJson")
    public TableDataInfo getReplyChkJson(QueryConditionVo queryConditionVo) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.getReplyChkJson(getSysUser().getUserId(), getSysUser().getDeptId(), queryConditionVo);
        return getDataTable(list);
    }

    /**
     * 进入审核本级回复 -- 未处理列表页面
     * @return 视图
     */
    @GetMapping("/peerReplyOverUntreatedM")
    public ModelAndView peerReplyOverUntreatedM() {
        return new ModelAndView(prefix + "/peerReplyOverUntreatedM");
    }

    /**
     * 加载审核本部门回复列表页面
     * 高新区
     */
    @PostMapping("/replyChkJsonData")
    public TableDataInfo replyChkJsonData(QueryConditionVo queryConditionVo) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.replyChkJsonData(getSysUser().getDeptId(), queryConditionVo);
        return getDataTable(list);
    }

    /**
     *  进入审核本级回复 -- 已处理列表页面 -- 本部门已办毕列表页面
     * @return 视图
     */
    @GetMapping("/peerReplyOverTreatedM")
    public ModelAndView peerReplyOverTreatedM() {
        return new ModelAndView(prefix + "/peerReplyOverTreatedM");
    }

    /**
     * 加载本部门已办毕列表数据
     * 高新区
     * @return 列表数据
     */
    @PostMapping("/replyOverJsonData")
    public TableDataInfo replyOverJsonData(QueryConditionVo queryConditionVo) {
        startPage();
        SysUser sysUser = getSysUser();
        String deptId = sysUser.getDeptId() == null ? null : sysUser.getDeptId().toString();
        List<Map<String, Object>> list = mwfSendBackService.replyOverJsonData(deptId, queryConditionVo);
        return getDataTable(list);
    }

    /**
     * 随机获取审核本级回复未处理工单
     * @return 视图
     */
    @GetMapping("/countAWaitPeerReplyM")
    public ModelAndView countAWaitPeerReplyM(ModelMap map) {
        map.put("num", mwfSendBackService.countReplyChkJson(getSysUser().getDeptId()));
        return new ModelAndView(prefix + "/countAWaitPeerReplyM");
    }

    /**
     * 随机获取审核本级回复未处理工单
     * @return 视图
     */
    @PostMapping("/getAWaitPeerReplyMCount")
    public AjaxResult getAWaitPeerReplyMCount() {
        return AjaxResult.success("获取成功",mwfSendBackService.countReplyChkJson(getSysUser().getDeptId()));
    }


    /**
     * 随机获取N条审核本级回复工单 并保存到中间表中
     */
    @PostMapping("/getAWaitPeerReplyList")
    @RequestBody
    public Object getAWaitPeerReplyList(Integer num) {
        SysUser user = ShiroUtils.getSysUser();
        List<MwfSendBack> list = new ArrayList<>();
        AjaxResult ajaxResult = new AjaxResult();
        try {
            list = mwfSendBackService.getAWaitPeerReplyList(num, user.getDeptId().toString());
            for (MwfSendBack mwfSendBack : list) {
                GetAWaitReplyMailEty mailEty = new GetAWaitReplyMailEty();
                mailEty.setSbId(mwfSendBack.getPkId());
                mailEty.setMailPkId(mwfSendBack.getWfId());
                mailEty.setUserNo(user.getUserNo());
                mailEty.setUserName(user.getUserName());
                mailEty.setDeptNo(user.getDeptId().toString());
                mailEty.setDeptName(user.getDeptName());
                mailEty.setCreateTime(new Date());
                if (getAWaitReplyMailService.checkBySbId(mailEty.getSbId())){
                    getAWaitReplyMailService.save(mailEty);
                }else{
                    ajaxResult.put("msg", "工单已被获取办理中，请刷新页面重试！");
                    return ajaxResult;
                }
            }
            ajaxResult.put("msg", "已成功获取到" + list.size() + "条数据");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ajaxResult.put("code", 0);
        return ajaxResult;
    }

    /**
     * 退回本单位审核工单
     *
     * @return 视图
     */
    @GetMapping("/backPeerDeptAuditM")
    public ModelAndView backPeerDeptAuditM() {
        return new ModelAndView(prefix + "/backPeerDeptAuditM");
    }

    /**
     * 加载退回本单位审核工单列表数据
     */
    @PostMapping("/backPeerDeptAuditMJson")
    public TableDataInfo backPeerDeptAuditMJson(QueryConditionVo queryConditionVo){
        startPage();
        List<Map<String, Object>> list;
        if (IS_GAOXIN()){
            list = mwfSendBackService.backPeerDeptAuditMJson_gxq(getSysUser().getDeptId(),queryConditionVo);
        }else{
            list = mwfSendBackService.backPeerDeptAuditMJson(getSysUser().getDeptId(),queryConditionVo);
        }
        return getDataTable(list);
    }

    /**
     * 进入退回本单位审核页面
     * @param sbId
     * @param map
     * @return
     */
    @GetMapping("/auditPeerBackM/{id}")
    public ModelAndView auditPeerBackM(@PathVariable("id")Integer sbId, ModelMap map) {
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbId);
        map.put("userRole",getSysUser().getRoles().get(0).getRoleId());
        if (mwfSendBack != null) {
            map.put("sendBackEty",mwfSendBack);
            MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(mwfSendBack.getWfId());
            map.put("workFormBase", mmailWorkForm);
            map.put("smsInform",smsNoteService.selectSmsInformMail(getSysUser().getDeptId().toString(), getSysUser().getUserId().toString()));
        }
        return new ModelAndView(prefix + "/auditPeerBackM");
    }

    /**
     * 退回本单位电话工单审核 退回审核数据
     *
     * @return
     */
    @PostMapping("/auditPeerBackMJson")
    public AjaxResult auditPeerBackMJson(MwfSendBack mwfSendBack,HttpServletRequest request) {
        boolean resultFlag; String opAction = "";
        String reason = request.getParameter("reason");
        SysUser user = ShiroUtils.getSysUser();
        int backState = mwfSendBack.getBackState();
        UpdateWrapper<MwfSendBack> updateWrapper = new UpdateWrapper<>();
        if (backState == 51){// 本级通过
            opAction = "审核通过";
            updateWrapper.set("SendState", 40)
                    .set("FlagInt", 1)
                    .set("GetTime", new Date())
                    .set("BackState", 11)
                    .set("GetPerson", user.getUserNo())
                    .set("GetPerTel", user.getPhonenumber())
                    .set("BackRemark", mwfSendBack.getBackRemark())
                    .set("SendRemark", "")
                    .eq("PkId", mwfSendBack.getPkId());
        }else if (backState == 60){// 本级不通过
            opAction = "审核不通过";
            if (reason.length() > 1){
                reason = mwfSendBack.getSendRemark()+"（"+ reason +"）";
            }else {
                reason = mwfSendBack.getSendRemark();
            }
            updateWrapper.set("SendState", backState)
                    .set("FlagInt", 0)
                    .set("GetTime", new Date())
                    .set("BackState", 12)
                    .set("GetPerson", user.getUserNo())
                    .set("GetPerTel", user.getPhonenumber())
                    .set("BackRemark", mwfSendBack.getBackRemark())
                    .set("SendRemark", reason)
                    .eq("PkId", mwfSendBack.getPkId());
        }
        resultFlag = mwfSendBackService.update(updateWrapper);
        if (resultFlag) {
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(mwfSendBack.getWfId());
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpBtnID(-1);
            etyLog.setOpAction("退回本级" + opAction);
            etyLog.setWsDesc("退回本级审核工单：" + opAction);
            if ("21".equals(mwfSendBack.getSortCode())) {
                etyLog.setWsOpen(0);
                etyLog.setEffectFlag(0);
            } else {
                etyLog.setWsOpen(1);
                etyLog.setEffectFlag(1);
            }
            etyLog.setOpDesc("退回本级审核: " + user.getDeptName() + "（" + opAction + "）");
            resultFlag = mMailWorkFormLogService.save(etyLog);
        }
        //更新父级派单状态
        commonDao.proMsubBackState(mwfSendBack.getWfId(),mwfSendBack.getPkId());
        return toAjax(resultFlag);
    }

    /**
     * 本单位不同意退回工单
     *
     * @return 视图
     */
    @GetMapping("/peerDeptNotPass")
    public ModelAndView peerDeptNotPass() {
        return new ModelAndView(prefix + "/peerDeptNotPass");
    }

    /**
     * 加载本单位不同意退回工单列表数据
     *
     * @return 列表数据
     */
    @PostMapping("/peerDeptNotPassJson")
    public TableDataInfo peerDeptNotPassJson(QueryConditionVo queryConditionVo) {
        startPage();
        List<Map<String, Object>> list = mwfSendBackService.peerDeptNotPassJson(getSysUser().getDeptId(),queryConditionVo);
        return getDataTable(list);
    }
}
